package traverser;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Scanner;

public class FrequencyCounter {

	Hashtable<String, Integer> frequencies;
	File freqFile = null;

	public FrequencyCounter(String fileName) {
		freqFile = new File(fileName);
		Scanner sc = null;

		try {
			if (!freqFile.exists()) {
				freqFile.createNewFile();
			}
			sc = new Scanner(freqFile);
		} catch (IOException e) {
			System.err.println("could not open frequency file");
			e.printStackTrace();
			//why here is a return 
			return;
		}

		if (sc.hasNextInt()) {
			frequencies = new Hashtable<String, Integer>(2 * sc.nextInt());
		} else {
			frequencies = new Hashtable<String, Integer>();
		}

		while (sc.hasNext()) {
			String page = sc.next();
			if (!sc.hasNextInt()) {
				System.err.println("Bad frequency file");
				return;
			}
			frequencies.put(page, sc.nextInt());
		}

		sc.close();
	}

	public int frequency(String page) {
		if (!frequencies.containsKey(page)) {
			return 0;
		}
		return frequencies.get(page);
	}

	public boolean contains(String page) {
		return frequencies.containsKey(page);
	}

	public void increment(String page) {
		if (!frequencies.containsKey(page)) {
			frequencies.put(page, 1);
			return;
		}
		frequencies.put(page, frequencies.get(page) + 1);
	}

	public void write() {
		PrintWriter out = null;
		try {
			out = new PrintWriter(new BufferedWriter(new FileWriter(freqFile)));
		} catch (IOException e) {
			System.err.println("Could not open file " + freqFile
					+ " for writing");
		}

		out.write("" + frequencies.size() + "\n");
		for (String page : frequencies.keySet()) {
			out.write(page + " " + frequencies.get(page) + "\n");
		}
		out.close();
	}

	public static void main(String[] args) {
		FrequencyCounter fq = new FrequencyCounter("test.freq");
		fq.increment("foo");
		fq.increment("bar");
		fq.increment("foo");
		fq.increment("cow");
		System.out.println(fq.frequency("foo"));
		System.out.println(fq.frequency("bar"));
		System.out.println(fq.frequency("blue"));
		fq.write();
	}

}
